package cn.whale.gateway.config;

import cn.whale.gateway.filter.KillStoreCheckFilter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

@EnableAutoConfiguration
@Configuration
@Log4j2
public class FilterReisterConfig {

    @Autowired
    private KillStoreCheckFilter requestFilter;

    private static final String SERVICE = "/kill/killCourse/kill";
    private static final String URI = "lb://kill-service";

    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {

        /*
        route1 是get请求，get请求使用readBody会报错
        route2 是post请求，Content-Type是application/x-www-form-urlencoded，readbody为String.class
        route3 是post请求，Content-Type是application/json,readbody为Object.class
         */
        RouteLocatorBuilder.Builder routes = builder.routes();
        RouteLocatorBuilder.Builder serviceProvider = routes
            .route("route1",r -> r
                    .method(HttpMethod.GET)
                    .and()
                    .path(SERVICE)
                    .filters(f -> {
                        f.stripPrefix(1).filter(requestFilter);
                        return f;
                    })
                    .uri(URI))
            .route("route2", r -> r
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .and()
                    .method(HttpMethod.POST)
                    .and()
                    .readBody(String.class, readBody -> {
                        return true;
                    })
                    .and()
                    .path(SERVICE)
                    .filters(f -> {
                        f.stripPrefix(1).filter(requestFilter);
                        return f;
                    })
                    .uri(URI))
            .route("route3", r -> r
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .and()
                    .method(HttpMethod.POST)
                    .and()
                    .readBody(Object.class, readBody -> {
                        return true;
                    })
                    .and()
                    .path(SERVICE)
                    .filters(f -> {
                        f.stripPrefix(1).filter(requestFilter);
                        return f;
                    })
                    .uri(URI));
        RouteLocator routeLocator = serviceProvider.build();
        return routeLocator;
    }
}
